import axios from 'axios'
// @ts-ignore
import buildURL from 'axios/lib/helpers/buildURL'
import type { AxiosRequestConfig } from 'axios'
import { redirectToLogin } from './index'

type ParamsSerializer = AxiosRequestConfig['paramsSerializer']

const whiteListUrl = [
  '/admin/we_chat/user-phone',
  '/admin/we_chat/unrestricted-qr-code'
]

export function getFullURL(
  baseURL: string,
  url: string,
  params: Record<string, any>,
  paramsSerializer?: ParamsSerializer
) {
  if (url.startsWith('http')) {
    return buildURL(url, params, paramsSerializer)
  }
  const calcBaseURL = baseURL.endsWith('/') ? baseURL : `${baseURL}/`
  const calcUrl = url.startsWith('/') ? url.slice(1) : url
  return buildURL(`${calcBaseURL}${calcUrl}`, params, paramsSerializer)
}

// 移除storage中的信息
export function removeStorage() {
  uni.removeStorageSync('token')
  uni.removeStorageSync('tenant_id')
  uni.removeStorageSync('userInfo')
  uni.removeStorageSync('supplier_code')
}

const createHttp = (option = { baseURL: '' }) => {
  const instance = axios.create({
    baseURL: import.meta.env.VITE_CUSTOMER_API,
    adapter(config) {
      const { url, method, data, params, headers, baseURL, paramsSerializer } =
        config
      return new Promise((resolve, reject) => {
        uni.request({
          method: method!.toUpperCase() as any,
          url: getFullURL(baseURL || '', url!, params, paramsSerializer),
          header: headers,
          data,
          dataType: 'json',
          responseType: config.responseType,
          success: (res: any) => {
            resolve({
              data: res,
              status: 200
            } as any)
          },
          fail: (err: any) => {
            reject(err)
          }
        })
      })
    }
  })

  /**
   * 请求拦截
   */
  instance.interceptors.request.use((config: any) => {
    const { method, params, headers: newHeaders } = config
    // 附带鉴权的token
    const token = uni.getStorageSync('token')
    let headers: any = {}
    headers.source = 'applet'
    if (token) {
      headers.Authorization = token
    }

    const tenant_id = uni.getStorageSync('tenant_id')
    if (tenant_id && !whiteListUrl.includes(config.url)) {
      headers['TENANT-ID'] = tenant_id
    }

    const supplier_code = uni.getStorageSync('supplier_code')
    if (supplier_code) {
      headers.SUPPLIER_CODE = supplier_code
    }

    headers = {
      ...headers,
      ...newHeaders
    }
    // 不缓存get请求
    if (method === 'get') {
      headers['Cache-Control'] = 'no-cache'
    }
    // delete请求参数放入body中
    if (method === 'delete') {
      headers['Content-type'] = 'application/json;'
      Object.assign(config, {
        data: params,
        params: {}
      })
    }

    if (
      method === 'post' &&
      (config.url as string).indexOf('auth/oauth/token') !== -1
    ) {
      // cGlnOnBpZw== c29jaWFsOnNvY2lhbA==
      headers.Authorization =
      (config.params.loginIdentity === 'SUPPLIER' || config.params.identity === 'SUPPLIER')
          ? 'Basic c3VwcGxpZXJfbWluaTpzdXBwbGllcl9taW5p'
          : 'Basic cHVyY2hhc2VfbWluaTpwdXJjaGFzZV9taW5p'
      headers['Content-type'] = 'application/x-www-form-urlencoded;'
      headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en;q=0.8;'
    }

    return {
      ...config,
      headers
    }
  })

  /**
   * 响应拦截
   */
  instance.interceptors.response.use((response) => {
    if (response.data?.statusCode === 424) {
      const token = uni.getStorageSync('token')
      if (token) {
        removeStorage()
        uni.showToast({
          icon: 'error',
          title: '登录过期'
        })
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/login/index'
          })
        }, 1500)
      } else {
        removeStorage()
        redirectToLogin()
      }

      setTimeout(() => {
        redirectToLogin()
      }, 1500)
      return response.data
    }
    // @ts-ignore
    // if ((response.status || response.statusCode) === 200) {
    if (response.data.statusCode === 200) {
      return response.data.data
    }

    if (
      response.data.statusCode === 500 &&
      (response.data.data?.errorCode === 'tenant_not_find_exception' ||
        response.data.data?.errorCode === 'not_find_exception')
    ) {
      setTimeout(() => {
        redirectToLogin()
      }, 1500)
    }
    const msg = response.data.data?.msg || '接口异常'
    if(msg?.length > 20) {
      wx.showModal({
        content: msg,
        showCancel: false
      });
    } else {
      uni.showToast({
        title: msg,
        duration: 2000,
        icon: 'none'
      })
    }
    // alert(v.statusText, '网络错误')
    return Promise.reject(response)
  })

  return instance
}

export const customerHttp = createHttp({
  baseURL: import.meta.env.VITE_CUSTOMER_API
})

export const fullHttp = createHttp()
